package com.chengn.threadlocal;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TransmittableThreadLocalTest {
    public static void main(String[] args) throws InterruptedException {
        TransmittableThreadLocal<Integer> transmittableThreadLocal = new TransmittableThreadLocal<>();

        transmittableThreadLocal.set(1);
        System.out.println(transmittableThreadLocal.get());
        new Thread(() -> {
            System.out.println("新建线程get：" + transmittableThreadLocal.get());
        }).start();

        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<>());
        ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(executor);
        for (int i = 0; i < 2; ++i) {
            transmittableThreadLocal.set(i);
            System.out.println("主方法get：" + transmittableThreadLocal.get());
            ttlExecutorService.execute(() -> {
                System.out.println("线程池get：" + transmittableThreadLocal.get());
            });

            TimeUnit.SECONDS.sleep(1);

        }

    }
}
